﻿using System;
using System.Collections.Generic;
using System.Text;

namespace GenerationCode.CSClasses
{
    class BaseDataAccess
    {
        private Utils.Table table;
        private string projectName;
        private string coder;
        private string email;
        private string objectClass;
        private string fieldValue;
        private string fieldDisplay;
        public BaseDataAccess(Utils.Table tb, string projectname, string coder, string email, string fieldValue, string fieldDisplay)
        {
            this.table = tb;
            this.projectName = projectname;
            this.coder = coder;
            this.email = email;
            this.fieldValue = fieldValue;
            this.fieldDisplay = fieldDisplay;

        }
        //set header 
        private string SetHeader()
        {
            string header = string.Format(@"/*
Author : {0}
Email  : {1}
Date   : {2} 

*/

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using {3};
using {4};
using System.Xml;        
namespace {5}{6}
      /// <summary>
    /// Define {7}DaoBase class. This class user for DataAccessLayer, contain 4 function Insert, Update, Search, Delete.
    /// If you want add new function, you must define in {7}Dao class , not here.
    /// </summary>
    public class {7}DaoBase {6}
    private static ILog logger = null;",
                this.coder, this.email, DateTime.Now.ToShortDateString(),Utils.Utility.BusinessObjectNamespace,Utils.Utility.UtilityNamespace,Utils.Utility.DataAccessNamespace,
                 "{", this.table.Name);
            return header;
        }
        private string SetParamsInsert()
        {
            string param = string.Empty;
            foreach (Utils.Column col in this.table.Columns)
            {

                if (!col.IsIdentity)
                {
                    if ((col.IsPK || inKeyList(col.Name)))
                    {
                        param += string.Format(@"
                 //Add value {0}  paramater.
				ManagerDao.AddInParameter(cmd, {0}, {1},{3}.{2});",
                        '"' + Utils.Utility.ConvertToPropertyName(col.Name) + '"',
                        Utils.Utility.ConvertParamType(col.SqlType),
                        Utils.Utility.ConvertToPropertyName(col.Name), Utils.Utility.insertUpdateObjectName);
                    }
                    else
                    {
                        param += string.Format(@"
                 //Add value {0}  paramater.
				ManagerDao.AddInParameter(cmd, {0}, {1},
					ConvertValueObject.CastObjValueToInsertDB({3}.{2}));",
                    '"' + Utils.Utility.ConvertToPropertyName(col.Name) + '"',
                    Utils.Utility.ConvertParamType(col.SqlType),
                    Utils.Utility.ConvertToPropertyName(col.Name), Utils.Utility.insertUpdateObjectName);
                    }
                }

            }
            return param;
        }

        //set parameter
        private string SetParamsSearch()
        {
            string param = string.Empty;
            foreach (Utils.Column col in this.table.Columns)
            {
                if (col.SqlType != "image")
                {

                    param += string.Format(@"
                    //Add value {0}  paramater.
				ManagerDao.AddInParameter(cmd, {0}, {1},
					ConvertValueObject.CastObjValueToInsertDB(t.{3}));",
                    '"' + Utils.Utility.ConvertToPropertyName(col.Name) + '"',
                    Utils.Utility.ConvertParamType(col.SqlType),
                    Utils.Utility.ConvertToPropertyName(col.DataType),
                    Utils.Utility.ConvertToPropertyName(col.Name));

                }

            }


            param += string.Format(@"
                //Add value SortField  paramater.
				ManagerDao.AddInParameter(cmd,{3}{0}{3}, {1},
				ConvertValueObject.CastObjValueToInsertDB(t.{0}));
                //Add value SortExpression  paramater.
                ManagerDao.AddInParameter(cmd,{3}{2}{3}, {1},
				ConvertValueObject.CastObjValueToInsertDB(t.{2}));                
                ", "SortField", "DbType.String", "SortExpression", '"');

            return param;
        }
        //set contructor
        private string SetConstructor()
        {
            string constructor = string.Format(@"
            #region Constructor
             /// <summary>
            /// Define Constructor.
             /// </summary>
            public {0}DaoBase(){1}{2}", table.Name, "{", "}");
            constructor += string.Format(@"
             static {0}DaoBase()
            {1}
            //Init logger.
            logger = LoggingUtility.GetLogger(typeof({0}DaoBase).FullName);
            {2}", table.Name, "{", "}");
            constructor += "\r\n #endregion";
            return constructor;

        }



        //set comon method
        private string CommonGetTable1DetailByDataReader(bool byLanguage)
        {
          //  byLanguage = false;
            string paraGetAllLanguage = string.Empty;

            string reader = string.Empty;
            if (byLanguage)
                reader = string.Format(@"
              /// <summary>
             /// Read data from IDataReader, convert to {0} Object.
            /// </summary>
            private static {0} Get{0}ByDataReader{4}(IDataReader reader,{5} {6})
    {1}
      String methodName = {3}Get{0}ByDataReader{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}
        try
      {1}
        {0} {7} = new {0}();", table.Name, "{", "}", '"', Utils.Utility.FunctionByLanguageName, Utils.Utility.LanguageIDFieldDataType, Utils.Utility.LanguageIDField, Utils.Utility.getObjectName);
            else
                reader = string.Format(@"
              /// <summary>
             /// Read data from IDataReader, convert to {0} Object.
            /// </summary>
            private static {0} Get{0}ByDataReader(IDataReader reader)
    {1}
      String methodName = {3}Get{0}ByDataReader{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}
        try
      {1}
        {0} {4} = new {0}();", table.Name, "{", "}", '"', Utils.Utility.getObjectName);
            foreach (Utils.Column col in table.Columns)
            {

                if ((col.IsPK || inKeyList(col.Name)) && col.Name != Utils.Utility.LanguageIDField)
                {

                    paraGetAllLanguage += Utils.Utility.getObjectName + "." + Utils.Utility.ConvertToPropertyName(col.Name) + ",";
                }

               
               /* if (col.DataType.ToUpper() == "int".ToUpper() || col.DataType.ToUpper() == "datetime".ToUpper())
                    s = string.Format(@"{0}.Parse(reader[{1}{2}{1}].ToString())", col.DataType, '"', Utils.Utility.ConvertToPropertyName(col.Name));
                else
                    s = string.Format(@"({0})reader[{1}{2}{1}]", col.DataType, '"', Utils.Utility.ConvertToPropertyName(col.Name));*/
                string s = col.DataType.ToLower();
                reader += string.Format(@"
              //read {2} field data.
             
            {1}.{2}=ManagerDao.Get{3}DataFromDataReader(reader,{0}{2}{0});
            ", '"', Utils.Utility.getObjectName, Utils.Utility.ConvertToPropertyName(col.Name), s);
            }
            //   paraGetAllLanguage += "," + Utils.Utility.LanguageIDFieldDataType + " " + Utils.Utility.LanguageIDField;
            paraGetAllLanguage = paraGetAllLanguage.Substring(0, paraGetAllLanguage.Length - 1);
            if (table.IsMultilanguage && !table.Name.Contains(Utils.Utility.MultilanguageTableName))
            {
                if (!byLanguage)
                    reader += string.Format("{4}.{0}{1}{2}={0}{1}Dao.GetAllLanguageofItem({3});", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, paraGetAllLanguage, Utils.Utility.getObjectName);
                else
                {
                    reader += string.Format("{3}.{0}{1}{2}=new List<{0}{1}>();", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, Utils.Utility.getObjectName);

                    reader += string.Format("{4}.{0}{1}{2}.Add({0}{1}Dao.Get({3}));", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, paraGetAllLanguage + "," + Utils.Utility.LanguageIDField, Utils.Utility.getObjectName);
                }

            }
            reader += string.Format(@"
             return {0};
      {2}
      catch (Exception e)
      {1}
        // write error to log file.
        logger.Error(methodName, e);
        return null;
      {2}
    {2}", Utils.Utility.getObjectName, "{", "}");
            return reader;
        }

        private string GetTable1ResultByDataReader_TotalRow(bool byLanguage)
        {
            string paraGetAllLanguage = string.Empty;
            string reader = string.Empty;
            if (!byLanguage)
                reader = string.Format(@"
             /// <summary>
             /// Read data from IDataReader, convert to {0}Result Object.
            /// </summary>
            ///<param name=""totalRow""> total of records in table Projects. </param>
         /*   private static {0}Result Get{0}ResultByDataReader(IDataReader reader,ref int totalRow)
    {1}
      String methodName = {3}Get{0}ResultByDataReader{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}
        try
      {1}
        {0}Result {4} = new {0}Result();", table.Name, "{", "}", '"', Utils.Utility.getObjectName);
            else
                reader = string.Format(@"
             /// <summary>
             /// Read data from IDataReader, convert to {0}Result Object.
            /// </summary>
            ///<param name=""totalRow""> total of records in table Projects. </param>
         /*   private static {0}Result Get{0}ResultByDataReader{4}(IDataReader reader,{5} {6},ref int totalRow)
    {1}
      String methodName = {3}Get{0}ResultByDataReader{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}
        try
      {1}
        {0}Result {7} = new {0}Result();", table.Name, "{", "}", '"', Utils.Utility.FunctionByLanguageName, Utils.Utility.LanguageIDFieldDataType, Utils.Utility.LanguageIDField, Utils.Utility.getObjectName);

            reader += string.Format(@"
            if (totalRow <= 0)
            {1}
                ////read TotalRow field data.
                totalRow=ManagerDao.Getint32DataFromDataReader(reader,{0}TotalRow{0});              
            {2}", '"', '{', '}');

            foreach (Utils.Column col in table.Columns)
            {

                if ((col.IsPK || inKeyList(col.Name)) && col.Name != Utils.Utility.LanguageIDField)
                {
                    paraGetAllLanguage += Utils.Utility.getObjectName + "." + Utils.Utility.ConvertToPropertyName(col.Name) + ",";
                }

              /*  string s = "";
                if (col.DataType.ToUpper() == "int".ToUpper() || col.DataType.ToUpper() == "datetime".ToUpper())
                    s = string.Format(@"{0}.Parse(reader[{1}{2}{1}].ToString())", col.DataType, '"', Utils.Utility.ConvertToPropertyName(col.Name));
                else
                    s = string.Format(@"({0})reader[{1}{2}{1}]", col.DataType, '"', Utils.Utility.ConvertToPropertyName(col.Name));*/
                string s = col.DataType.ToLower();
                reader += string.Format(@"
                //read {2} field data.
                    {4}.{2} =ManagerDao.Get{3}DataFromDataReader(reader,{0}{2}{0});
            ", '"', table.Name, Utils.Utility.ConvertToPropertyName(col.Name), s, Utils.Utility.getObjectName);
            }
            paraGetAllLanguage = paraGetAllLanguage.Substring(0, paraGetAllLanguage.Length - 1);
          /*  if (table.IsMultilanguage && !table.Name.Contains(Utils.Utility.MultilanguageTableName))
            {
                if (!byLanguage)
                    reader += string.Format("{4}.{0}{1}{2}={0}{1}Dao.GetAllLanguageofItem({3});", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, paraGetAllLanguage, Utils.Utility.getObjectName);
                else
                {
                    reader += string.Format("{3}.{0}{1}{2}=new List<{0}{1}>();", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, Utils.Utility.getObjectName);
                    reader += string.Format("{4}.{0}{1}{2}.Add({0}{1}Dao.Get({3}));", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, paraGetAllLanguage + "," + Utils.Utility.LanguageIDField, Utils.Utility.getObjectName);
                }
            }*/
            reader += string.Format(@"
             return {0};
      {2}
      catch (Exception e)
      {1}
        // write error to log file.
        logger.Error(methodName, e);
        return null;
      {2}
    {2}*/", Utils.Utility.getObjectName, "{", "}");
            return reader;
        }
        /// <summary>
        /// Get object not return Total Row
        /// </summary>
        /// <returns></returns>
        private string GetTable1ResultByDataReader(bool byLanguage)
        {
            string paraGetAllLanguage = string.Empty;
            string reader = string.Empty;
            if (!byLanguage)
                reader = string.Format(@"
            /// <summary>
             /// Read data from IDataReader, convert to {0}Result Object.
            /// </summary>
            private static {0}Result Get{0}ResultByDataReader(IDataReader reader)
    {1}
      String methodName = {3}Get{0}ResultByDataReader{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}
        try
      {1}
        {0}Result {4} = new {0}Result();", table.Name, "{", "}", '"', Utils.Utility.getObjectName);
            else
                reader = string.Format(@"
            /// <summary>
             /// Read data from IDataReader, convert to {0}Result Object.
            /// </summary>
            private static {0}Result Get{0}ResultByDataReader{4}(IDataReader reader,{5} {6})
    {1}
      String methodName = {3}Get{0}ResultByDataReader{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}
        try
      {1}
        {0}Result {7} = new {0}Result();", table.Name, "{", "}", '"', Utils.Utility.FunctionByLanguageName, Utils.Utility.LanguageIDFieldDataType, Utils.Utility.LanguageIDField, Utils.Utility.getObjectName);

            foreach (Utils.Column col in table.Columns)
            {

                if ((col.IsPK || inKeyList(col.Name)) && col.Name != Utils.Utility.LanguageIDField)
                {
                    paraGetAllLanguage += Utils.Utility.getObjectName + "." + Utils.Utility.ConvertToPropertyName(col.Name) + ",";
                }

               // string s = "";
               /* if (col.DataType.ToUpper() == "int".ToUpper() || col.DataType.ToUpper() == "datetime".ToUpper())
                    s = string.Format(@"{0}.Parse(reader[{1}{2}{1}].ToString())", col.DataType, '"', Utils.Utility.ConvertToPropertyName(col.Name));
                else
                    s = string.Format(@"({0})reader[{1}{2}{1}]", col.DataType, '"', Utils.Utility.ConvertToPropertyName(col.Name));*/
                string s = col.DataType.ToLower();

                reader += string.Format(@"
            //read {2} field data.
             {4}.{2} =ManagerDao.Get{3}DataFromDataReader(reader,{0}{2}{0});
            ", '"', table.Name, Utils.Utility.ConvertToPropertyName(col.Name), s, Utils.Utility.getObjectName);
            }
            paraGetAllLanguage = paraGetAllLanguage.Substring(0, paraGetAllLanguage.Length - 1);
           /* if (table.IsMultilanguage && !table.Name.Contains(Utils.Utility.MultilanguageTableName))
            {
                if (!byLanguage)
                    reader += string.Format("{4}.{0}{1}{2}={0}{1}Dao.GetAllLanguageofItem({3});", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, paraGetAllLanguage, Utils.Utility.getObjectName);
                else
                {
                    reader += string.Format("{3}.{0}{1}{2}=new List<{0}{1}>();", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, Utils.Utility.getObjectName);
                    reader += string.Format("{4}.{0}{1}{2}.Add({0}{1}Dao.Get({3}));", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, paraGetAllLanguage + "," + Utils.Utility.LanguageIDField, Utils.Utility.getObjectName);
                }
            }*/
            reader += string.Format(@"
             return {0};
      {2}
      catch (Exception e)
      {1}
        // write error to log file.
        logger.Error(methodName, e);
        return null;
      {2}
    {2}", Utils.Utility.getObjectName, "{", "}");
            return reader;
        }
        private string SetCommonInsert()
        {
            if (table.IsMultilanguage)
                return SetCommonInsertMultilanguage();
            return SetCommonInsertNotMultilanguage();
        }

        private string SetCommonInsertNotMultilanguage()
        {
            //insesrt
            string insert = string.Empty;
            List<Utils.Column> lstPK = new List<GenerationCode.Utils.Column>();//list primary key of this table
            string column = "";
            string columntype = "";
            foreach (Utils.Column col in table.Columns)
            {
                if (col.IsPK || inKeyList(col.Name))
                {
                    lstPK.Add(col);
                }
            }
            if (!lstPK[0].IsIdentity)//PK must be input from UI layer, insert and return true/false
            {
                insert = string.Format(@"
              /// <summary>
        /// Define function Insert for {0} Object.
        /// </summary>
        /// <param name=""{4}"">Object Insert.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
            public static bool Insert({0} {4})
            {1}
                bool result = false;
              String methodName = {2}Insert{0}{2};
              if (logger.IsDebugEnabled)
              {1}
                LoggingUtility.logMethodEntry(logger, methodName);
              {3}
              DbCommand cmd = ManagerDao.GetStoredProcCommand({2}spInsert{0}{2});            
            ", table.Name, "{", '"', "}", Utils.Utility.insertUpdateObjectName);
                insert += SetParamsInsert();
                insert += string.Format(@"    
            //add paramater store return value.        
             ManagerDao.AddParameter(cmd, {0}returnValue{0}, DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
              {1}
                ManagerDao.ExecuteNonQuery(cmd);
                int id = (int)ManagerDao.GetParameterValue(cmd, {0}returnValue{0});
                if (id>0)//Successfull.
                {1}
                  result = true;
                {2}
                else//Error.
                {1}
                  result = false;
                {2}
              {2}
              catch (Exception e)
              {1}
                //write error message to log file.
                logger.Error(methodName, e);
                result = false;
              {2}
              return result;
            {2}
             ", '"', "{", "}", column, columntype);
            }
            else
            {
                string dbType = Utils.Utility.ConvertParamType(lstPK[0].SqlType);
                insert = string.Format(@"
              /// <summary>
        /// Define function Insert for {0} Object.
        /// </summary>
        /// <param name=""{4}"">Object Insert.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
            public static bool Insert({0} {4})
            {1}
                bool result = false;
              String methodName = {2}Insert{0}{2};
              if (logger.IsDebugEnabled)
              {1}
                LoggingUtility.logMethodEntry(logger, methodName);
              {3}
              DbCommand cmd = ManagerDao.GetStoredProcCommand({2}spInsert{0}{2});            
            ", table.Name, "{", '"', "}", Utils.Utility.insertUpdateObjectName);
                insert += SetParamsInsert();
                insert += string.Format(@"    
            //add paramater store return value.        
             ManagerDao.AddParameter(cmd, {0}returnValue{0}, DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
              {1}
                ManagerDao.ExecuteNonQuery(cmd);
                  " + dbType.Substring(7) + @" id = " + dbType.Substring(7) + @".Parse(ManagerDao.GetParameterValue(cmd, {0}returnValue{0}).ToString());
              
                if (id>0)//Successfull.
                {1}
                  result = true;
                {2}
                else//Error.
                {1}
                  result = false;
                {2}
              {2}
              catch (Exception e)
              {1}
                //write error message to log file.
                logger.Error(methodName, e);
                result = false;
              {2}
              return result;
            {2}
             ", '"', "{", "}", column, columntype);
            }

            return insert;
        }
        private string SetCommonInsertMultilanguage()
        {
            //insesrt
            string result = string.Empty;
            List<Utils.Column> lstPK = new List<GenerationCode.Utils.Column>();//list primary key of this table
            string column = "";
            string columntype = "";
            foreach (Utils.Column col in table.Columns)
            {
                if (col.IsPK || inKeyList(col.Name))
                {
                    lstPK.Add(col);
                }
            }
            if (!lstPK[0].IsIdentity)//PK must be input from UI layer, insert and return true/false
            {
                //                string paraInsertPK = string.Empty;//para for PK, add to store Insert                
                //                foreach (Utils.Column col in lstPK)
                //                {

                //                    paraInsertPK += string.Format(@"
                //                         //Add value {0}  paramater.
                //				        ManagerDao.AddInParameter(cmd, {0}, {1},{3}.{2});",
                //                       '"' + Utils.Utility.ConvertToPropertyName(col.Name) + '"',
                //                       Utils.Utility.ConvertParamType(col.SqlType),
                //                       Utils.Utility.ConvertToPropertyName(col.Name), Utils.Utility.insertUpdateObjectName);
                //                }
                result = string.Format(@"
              /// <summary>
        /// Define function Insert for {0} Object.
        /// </summary>
        /// <param name=""{4}"">Object Insert.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
            public static bool Insert({0} {4})
            {1}
               
              String methodName = {2}Insert{0}{2};
                ManagerDao.BeginTransaction();
              if (logger.IsDebugEnabled)
              {1}
                LoggingUtility.logMethodEntry(logger, methodName);
              {3}
              DbCommand cmd = ManagerDao.GetStoredProcCommand({2}spInsert{0}{2});            
            ", table.Name, "{", '"', "}", Utils.Utility.insertUpdateObjectName);
                result += SetParamsInsert();
                result += string.Format(@"    
            //add paramater store return value.        
             ManagerDao.AddParameter(cmd, {0}returnValue{0}, DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
              {1}
                ManagerDao.ExecuteNonQuery(cmd);
                int id = (int)ManagerDao.GetParameterValue(cmd, {0}returnValue{0});
                if (id>0)//Successfull.
                {1}
                      if({8}.{5}{6}{7} !=null && {8}.{5}{6}{7}.Count>0)
                      {1}
                          foreach ({5}{6} o in {8}.{5}{6}{7})
                            {1}
                              if (o!=null)
                              {1}                              
                                if(!{5}{6}Dao.Insert(o))
                                {1}
                                     ManagerDao.Rollback();  
                                     return false;                                 
                                {2}
                              {2}
                              
                            {2}
                       {2}
                       ManagerDao.Commit();  
                       return true;   

                {2}              
              {2}
              catch (Exception e)
              {1}
                //write error message to log file.
                logger.Error(methodName, e);              
              {2}
              ManagerDao.Rollback();  
              return false;                  
            {2}
             ", '"', "{", "}", column, columntype, table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, Utils.Utility.insertUpdateObjectName);
            }
            else//has one PK, and it auto Increament
            {
                string dbType = Utils.Utility.ConvertParamType(lstPK[0].SqlType);

                result = string.Format(@"
              /// <summary>
        /// Define function Insert for {0} Object.
        /// </summary>
        /// <param name=""{4}"">Object Insert.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
            public static bool Insert({0} {4})
            {1}
               
              String methodName = {2}Insert{0}{2};
                ManagerDao.BeginTransaction();
              if (logger.IsDebugEnabled)
              {1}
                LoggingUtility.logMethodEntry(logger, methodName);
              {3}
              DbCommand cmd = ManagerDao.GetStoredProcCommand({2}spInsert{0}{2});            
            ", table.Name, "{", '"', "}", Utils.Utility.insertUpdateObjectName);
                result += SetParamsInsert();
                result += string.Format(@"    
            //add paramater store return value.        
             ManagerDao.AddParameter(cmd, {0}returnValue{0}, " + dbType + @", ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
              {1}
                ManagerDao.ExecuteNonQuery(cmd);
                " + dbType.Substring(7) + @" id = " + dbType.Substring(7) + @".Parse(ManagerDao.GetParameterValue(cmd, {0}returnValue{0}).ToString());
                if (id>0)//Successfull.
                {1}
                      if({8}.{5}{6}{7} !=null && {8}.{5}{6}{7}.Count>0)
                      {1}
                          foreach ({5}{6} o in {8}.{5}{6}{7})
                            {1}
                              if (o!=null)
                              {1}
                                o.{3}=id;
                                if(!{5}{6}Dao.Insert(o))
                                {1}
                                     ManagerDao.Rollback();  
                                     return false;                                 
                                {2}
                              {2}
                              
                            {2}
                       {2}
                       ManagerDao.Commit();  
                       return true;   

                {2}              
              {2}
              catch (Exception e)
              {1}
                //write error message to log file.
                logger.Error(methodName, e);              
              {2}
              ManagerDao.Rollback();  
              return false;                  
            {2}
             ", '"', "{", "}", Utils.Utility.ConvertToPropertyName(lstPK[0].Name), lstPK[0].DataType, table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, Utils.Utility.insertUpdateObjectName);
            }

            return result;

        }
        /*private string SetCommonInsertMultilanguage()
        {
            //insesrt
            string column = "";
            string columntype = "";
            foreach (Utils.Column col in table.Columns)
            {
                if (col.IsPK || inKeyList(col.Name))
                {
                    column = Utils.Utility.ConvertToPropertyName(col.Name);
                    columntype = col.DataType;
                    break;
                }
            }
            string insert = string.Format(@"
              /// <summary>
        /// Define function Insert for {0} Object.
        /// </summary>
        /// <param name=""{4}"">Object Insert.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
            public static bool Insert({0} {4})
            {1}
               
              String methodName = {2}Insert{0}{2};
                ManagerDao.BeginTransaction();
              if (logger.IsDebugEnabled)
              {1}
                LoggingUtility.logMethodEntry(logger, methodName);
              {3}
              DbCommand cmd = ManagerDao.GetStoredProcCommand({2}spInsert{0}{2});            
            ", table.Name, "{", '"', "}",Utils.Utility.insertUpdateObjectName);
            insert += SetParamsInsert();
            insert += string.Format(@"    
            //add paramater store return value.        
             ManagerDao.AddParameter(cmd, {0}returnValue{0}, DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
              {1}
                ManagerDao.ExecuteNonQuery(cmd);
                int id = (int)ManagerDao.GetParameterValue(cmd, {0}returnValue{0});
                if (id>0)//Successfull.
                {1}
                      if({8}.{5}{6}{7} !=null && {8}.{5}{6}{7}.Count>0)
                      {1}
                          foreach ({5}{6} o in {8}.{5}{6}{7})
                            {1}
                              if (o!=null)
                              {1}
                                o.{3}=id;
                                if(!{5}{6}Dao.Insert(o))
                                {1}
                                     ManagerDao.Rollback();  
                                     return false;                                 
                                {2}
                              {2}
                              
                            {2}
                       {2}
                       ManagerDao.Commit();  
                       return true;   

                {2}              
              {2}
              catch (Exception e)
              {1}
                //write error message to log file.
                logger.Error(methodName, e);              
              {2}
              ManagerDao.Rollback();  
              return false;                  
            {2}
             ", '"', "{", "}", column, columntype, table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList,Utils.Utility.insertUpdateObjectName);
            return insert;

        }*/
        private string CommonUpdate()
        {
            if (table.IsMultilanguage)
                return CommonUpdateMultilanguage() + CommonInsertUpdate();
            return CommonUpdateNotMultilanguage() + CommonInsertUpdate();
        }

        private string CommonInsertUpdate()
        {
            if (this.table.Name.Contains(Utils.Utility.MultilanguageTableName))
            {
                string updateStrorePara = string.Empty;
                foreach (Utils.Column col in table.Columns)
                {
                    string propertyName = string.Empty;

                    if (!col.IsIdentity || (col.IsIdentity && (col.IsPK || inKeyList(col.Name))))
                    {
                        propertyName = Utils.Utility.ConvertToPropertyName(col.Name);

                        updateStrorePara += string.Format(@"
                 //Add value {0}  paramater.
				ManagerDao.AddInParameter(cmd, {0}, {1},ConvertValueObject.CastObjValueToInsertDB({2}.{3}));", '"' + propertyName + '"',
                                             Utils.Utility.ConvertParamType(col.SqlType), Utils.Utility.insertUpdateObjectName, propertyName);

                    }
                }

                string update = string.Format(@"
               /// <summary>
        /// Define function InsertUpdate for {0} Object.
        /// </summary>
        /// <param name=""{4}"">Object Update.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
            public static bool InsertUpdate({0} {4})
          {2}
          bool result = false;
          String methodName = {1}InsertUpdate{0}{1};
          if (logger.IsDebugEnabled)
          {2}
            LoggingUtility.logMethodEntry(logger, methodName);
          {3}
             DbCommand cmd = ManagerDao.GetStoredProcCommand({1}spInsertUpdate{0}{1});
           ", table.Name, '"', "{", "}", Utils.Utility.insertUpdateObjectName);

                update += "\r\n" + updateStrorePara;

                update += string.Format(@"           
            // add parameter store return value.
             ManagerDao.AddParameter(cmd, {0}returnValue{0}, DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
           try
          {2}
            ManagerDao.ExecuteNonQuery(cmd);
            int rows = (int)ManagerDao.GetParameterValue(cmd, {0}returnValue{0});
            if (rows == 1)//Successfull.
            {2}
              result = true;
            {3}
            else//Error.
            {2}
              result = false;
            {3}

          {3}
          catch (Exception e)
          {2}
            //write error Message to log file.
            logger.Error(methodName, e);
            result = false;
          {3}
          return result;
                {3}", '"', table.Name, "{", "}");
                return update;
            }
            return string.Empty;
        }

        private string CommonUpdateMultilanguage()
        {
            string updateStrorePara = string.Empty;
            //   string updateStroreParaPK = string.Empty;
            foreach (Utils.Column col in table.Columns)
            {
                string propertyName = string.Empty;

                /* if (!col.IsIdentity || (col.IsIdentity && (col.IsPK || inKeyList(col.Name))))
                 {
                     propertyName = Utils.Utility.ConvertToPropertyName(col.Name);

                     updateStrorePara += string.Format(@"
                  //Add value {0}  paramater.
                 ManagerDao.AddInParameter(cmd, {0}, {1},ConvertValueObject.CastObjValueToInsertDB({2}.{3}));", '"' + propertyName + '"', Utils.Utility.ConvertParamType(col.SqlType), Utils.Utility.insertUpdateObjectName, propertyName);


                 }*/
                if (col.IsPK || inKeyList(col.Name))
                {

                    propertyName = Utils.Utility.ConvertToPropertyName(col.Name);
                    updateStrorePara += string.Format(@"
                    //Add value {0}  paramater.
				    ManagerDao.AddInParameter(cmd, {0}, {1},{2}.{3});", '"' + propertyName + '"', Utils.Utility.ConvertParamType(col.SqlType), Utils.Utility.insertUpdateObjectName, propertyName);

                }
                else
                {
                    propertyName = Utils.Utility.ConvertToPropertyName(col.Name);

                    updateStrorePara += string.Format(@"
                 //Add value {0}  paramater.
				ManagerDao.AddInParameter(cmd, {0}, {1},ConvertValueObject.CastObjValueToInsertDB({2}.{3}));", '"' + propertyName + '"', Utils.Utility.ConvertParamType(col.SqlType), Utils.Utility.insertUpdateObjectName, propertyName);
                }
            }

            string update = string.Format(@"
               /// <summary>
        /// Define function Update for {0} Object.
        /// </summary>
        /// <param name=""{4}"">Object Update.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
            public static bool Update({0} {4})
          {2}
          String methodName = {1}Update{0}{1};
             ManagerDao.BeginTransaction();
          if (logger.IsDebugEnabled)
          {2}
            LoggingUtility.logMethodEntry(logger, methodName);
          {3}
             DbCommand cmd = ManagerDao.GetStoredProcCommand({1}spUpdate{0}{1});
           ", table.Name, '"', "{", "}", Utils.Utility.insertUpdateObjectName);

            update += "\r\n" + updateStrorePara;

            update += string.Format(@"           
            // add parameter store return value.
             ManagerDao.AddParameter(cmd, {0}returnValue{0}, DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
           try
          {2}
            ManagerDao.ExecuteNonQuery(cmd);
            int rows = (int)ManagerDao.GetParameterValue(cmd, {0}returnValue{0});
            if (rows == 1)//Successfull.
            {2}
                 if({7}.{4}{5}{6} !=null && {7}.{4}{5}{6}.Count>0)
                      {2}
                          foreach ({4}{5} o in {7}.{4}{5}{6})
                            {2}
                              if (o!=null)
                              {2}
                               
                                if(!{4}{5}Dao.InsertUpdate(o))
                                {2}
                                     ManagerDao.Rollback();  
                                     return false;                                 
                                {3}
                              {3}
                              
                            {3}
                       {3}
                       ManagerDao.Commit();  
                       return true;   
            {3}          

          {3}
          catch (Exception e)
          {2}
            //write error Message to log file.
            logger.Error(methodName, e);           
          {3}
           ManagerDao.Rollback();  
           return false;    
                {3}", '"', table.Name, "{", "}", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList, Utils.Utility.insertUpdateObjectName);
            return update;
        }
        private string CommonUpdateNotMultilanguage()
        {
            string updateStrorePara = string.Empty;
            foreach (Utils.Column col in table.Columns)
            {
                string propertyName = string.Empty;

                if (!col.IsIdentity || (col.IsIdentity && (col.IsPK || inKeyList(col.Name))))
                {
                    propertyName = Utils.Utility.ConvertToPropertyName(col.Name);

                    updateStrorePara += string.Format(@"
                 //Add value {0}  paramater.
				ManagerDao.AddInParameter(cmd, {0}, {1},ConvertValueObject.CastObjValueToInsertDB({2}.{3}));", '"' + propertyName + '"',
                                         Utils.Utility.ConvertParamType(col.SqlType), Utils.Utility.insertUpdateObjectName,
                                         propertyName);

                }
            }

            string update = string.Format(@"
               /// <summary>
        /// Define function Update for {0} Object.
        /// </summary>
        /// <param name=""{4}"">Object Update.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
            public static bool Update({0} {4})
          {2}
          bool result = false;
          String methodName = {1}Update{0}{1};
          if (logger.IsDebugEnabled)
          {2}
            LoggingUtility.logMethodEntry(logger, methodName);
          {3}
             DbCommand cmd = ManagerDao.GetStoredProcCommand({1}spUpdate{0}{1});
           ", table.Name, '"', "{", "}", Utils.Utility.insertUpdateObjectName);

            update += "\r\n" + updateStrorePara;

            update += string.Format(@"           
            // add parameter store return value.
             ManagerDao.AddParameter(cmd, {0}returnValue{0}, DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
           try
          {2}
            ManagerDao.ExecuteNonQuery(cmd);
            int rows = (int)ManagerDao.GetParameterValue(cmd, {0}returnValue{0});
            if (rows == 1)//Successfull.
            {2}
              result = true;
            {3}
            else//Error.
            {2}
              result = false;
            {3}

          {3}
          catch (Exception e)
          {2}
            //write error Message to log file.
            logger.Error(methodName, e);
            result = false;
          {3}
          return result;
                {3}", '"', table.Name, "{", "}");
            return update;
        }
        private string CommonGetByLanguage()
        {
            return string.Empty;
            if (!table.IsMultilanguage)
                return string.Empty;
            string commentParamater = string.Empty;
            string comment = string.Empty;
            string strPkParamater = string.Empty;
            string column = "";
            foreach (Utils.Column col in table.Columns)
            {
                if (col.IsPK || inKeyList(col.Name))
                {
                    strPkParamater = strPkParamater + col.DataType + " " + col.Name + ",";
                    commentParamater += "/// <param name={0}" + col.Name + "{0} >This is primary key to get data.</param>\r\n";
                }
            }
            commentParamater = string.Format(commentParamater, '"');
            comment = "\r\n/// <summary>\r\n";
            comment += "/// Get Data " + table.Name + " object. \r\n";
            comment += "/// </summary>\r\n";
            comment += commentParamater;
            comment += "/// <returns>" + table.Name + " object.</returns>\r\n";

            strPkParamater = strPkParamater.Substring(0, strPkParamater.Length - 1);
            string strGet = comment + @"              
           public static " + this.table.Name + " Get" + Utils.Utility.FunctionByLanguageName + "(" + strPkParamater + "," + Utils.Utility.LanguageIDFieldDataType + " " + Utils.Utility.LanguageIDField + string.Format(@")
    {1}
      String methodName = {3}Get{0}{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}
      try
      {1}
        {0} {4} = null;
        DbCommand dbCommnand = ManagerDao.GetStoredProcCommand({3}spGet{0}{3});", table.Name, "{", "}", '"', Utils.Utility.getObjectName);
            strGet += SetParamFunctionGet();
            strGet += string.Format(@"
        IDataReader reader = ManagerDao.ExecuteReader(dbCommnand);
        if (reader.Read())
        {1}
          {6}= Get{0}ByDataReader{4}(reader,{5});

        {2}
        reader.Close();
        return {6};
      {2}
      catch (System.Exception e)
      {1}
        //write error message to log file.
        logger.Error({3}Get{3}, e);
        return null;
      {2}
    {2}", table.Name, "{", "}", '"', Utils.Utility.FunctionByLanguageName, Utils.Utility.LanguageIDField, Utils.Utility.getObjectName);

            return strGet;



        }

        private string CommonGet()
        {
            string commentParamater = string.Empty;
            string comment = string.Empty;
            string strPkParamater = string.Empty;
            string column = "";
            foreach (Utils.Column col in table.Columns)
            {
                if (col.IsPK || inKeyList(col.Name))
                {
                    strPkParamater = strPkParamater + col.DataType + " " + col.Name + ",";
                    commentParamater += "/// <param name={0}" + col.Name + "{0} >This is primary key to get data.</param>\r\n";
                }
            }
            commentParamater = string.Format(commentParamater, '"');
            comment = "\r\n/// <summary>\r\n";
            comment += "/// Get Data " + table.Name + " object. \r\n";
            comment += "/// </summary>\r\n";
            comment += commentParamater;
            comment += "/// <returns>" + table.Name + " object.</returns>\r\n";

            strPkParamater = strPkParamater.Substring(0, strPkParamater.Length - 1);
            string strGet = comment + @"              
           public static " + this.table.Name + " Get(" + strPkParamater + string.Format(@")
    {1}
      String methodName = {3}Get{0}{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}
      try
      {1}
        {0} {4} = null;
        DbCommand dbCommnand = ManagerDao.GetStoredProcCommand({3}spGet{0}{3});", table.Name, "{", "}", '"', Utils.Utility.getObjectName);
            strGet += SetParamFunctionGet();
            strGet += string.Format(@"
        IDataReader reader = ManagerDao.ExecuteReader(dbCommnand);
        if (reader.Read())
        {1}
          {4}= Get{0}ByDataReader(reader);

        {2}
        reader.Close();
        return result;
      {2}
      catch (System.Exception e)
      {1}
        //write error message to log file.
        logger.Error({3}Get{3}, e);
        return null;
      {2}
    {2}", table.Name, "{", "}", '"', Utils.Utility.getObjectName);

            return strGet;



        }

        private bool inKeyList(string p)
        {

            foreach (object col in table.KeyList)
            {
                if (col.ToString().Trim() == p.Trim())
                    return true;

            }
            return false;
        }


        private string GetAllLanguageofItem()
        {
            if (!table.Name.Contains(Utils.Utility.MultilanguageTableName))
                return string.Empty;
            string comment = string.Empty;
            string deleteStrorePara = string.Empty;
            string deleteFunctionPara = string.Empty;

            foreach (Utils.Column col in table.Columns)
            {
                string propertyName = string.Empty;
                if ((col.IsPK || inKeyList(col.Name)) && col.Name.Trim().ToLower() != Utils.Utility.LanguageIDField.Trim().ToLower())
                {
                    propertyName = Utils.Utility.ConvertToPropertyName(col.Name);

                    deleteStrorePara += string.Format(@"
                //Add value {0}  paramater.
				ManagerDao.AddInParameter(dbCommand, {0}, {1},{2});", '"' + propertyName + '"',
                                         Utils.Utility.ConvertParamType(col.SqlType), propertyName);
                    deleteFunctionPara += col.DataType + " " + propertyName + ",";
                }
            }
            deleteFunctionPara = deleteFunctionPara.Substring(0, deleteFunctionPara.Length - 1);

            string getall = string.Format(@"
              /// <summary>
        /// Get All Language of {0} object from table {0}.
        /// </summary>
        /// <returns>List {0} object.</returns>
             public static List<{0}> GetAllLanguageofItem({4})
                {1}
                 String methodName = {3}GetAllLanguageofItem{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}

      try
      {1}
        List<{0}> list{0} = new List<{0}>();
        DbCommand dbCommand = ManagerDao.GetStoredProcCommand({3}spGetAllLanguageofItem{0}{3});
        {5}
        using (IDataReader reader = ManagerDao.ExecuteReader(dbCommand))
        {1}
          while (reader.Read())
          {1}
            list{0}.Add(Get{0}ByDataReader(reader));
          {2}
          reader.Close();
        {2}

        return list{0};
      {2}
      catch (Exception ex)
      {1}
        //write error message to log file.
        logger.Error(methodName, ex);
        return null;
      {2}
    {2}
", table.Name, "{", "}", '"', deleteFunctionPara, deleteStrorePara);
            return getall;
        }


        private string ComonGetallByLanguage()
        {
            return string.Empty;
            if (!table.IsMultilanguage)
                return string.Empty;
            string getall = string.Format(@"
              /// <summary>
        /// Get All {0} object from table {0}.
        /// </summary>
        /// <returns>List {0} object.</returns>
             public static List<{0}> GetAll{5}({4})
                {1}
                 String methodName = {3}GetAll{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}

      try
      {1}
        List<{0}> list{0} = new List<{0}>();
        DbCommand dbCommand = ManagerDao.GetStoredProcCommand({3}spGetAll{0}{3});

        using (IDataReader reader = ManagerDao.ExecuteReader(dbCommand))
        {1}
          while (reader.Read())
          {1}
            list{0}.Add(Get{0}ByDataReader{5}(reader,{6}));
          {2}
          reader.Close();
        {2}

        return list{0};
      {2}
      catch (Exception ex)
      {1}
        //write error message to log file.
        logger.Error(methodName, ex);
        return null;
      {2}
    {2}
", table.Name, "{", "}", '"', Utils.Utility.LanguageIDFieldDataType + " " + Utils.Utility.LanguageIDField, Utils.Utility.FunctionByLanguageName, Utils.Utility.LanguageIDField);
            return getall;
        }

        private string ComonGetall()
        {
            string getall = string.Format(@"
              /// <summary>
        /// Get All {0} object from table {0}.
        /// </summary>
        /// <returns>List {0} object.</returns>
             public static List<{0}Result> GetAll()
                {1}
                 String methodName = {3}GetAll{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}

      try
      {1}
        List<{0}Result> list{0} = new List<{0}Result>();
        DbCommand dbCommand = ManagerDao.GetStoredProcCommand({3}spGetAll{0}{3});

        using (IDataReader reader = ManagerDao.ExecuteReader(dbCommand))
        {1}
          while (reader.Read())
          {1}
            list{0}.Add(Get{0}ResultByDataReader(reader));
          {2}
          reader.Close();
        {2}

        return list{0};
      {2}
      catch (Exception ex)
      {1}
        //write error message to log file.
        logger.Error(methodName, ex);
        return null;
      {2}
    {2}
", table.Name, "{", "}", '"');
            return getall;
        }
        private string ComonDelete()
        {

            string comment = string.Empty;
            string commentPara = string.Empty;
            string deleteStrorePara = string.Empty;
            string deleteFunctionPara = string.Empty;

            foreach (Utils.Column col in table.Columns)
            {
                string propertyName = string.Empty;
                if (col.IsPK || inKeyList(col.Name))
                {
                    propertyName = Utils.Utility.ConvertToPropertyName(col.Name);

                    deleteStrorePara += string.Format(@"
                //Add value {0}  paramater.
				ManagerDao.AddInParameter(dbCommand, {0}, {1},{2});", '"' + propertyName + '"',
                                         Utils.Utility.ConvertParamType(col.SqlType), propertyName);
                    deleteFunctionPara += col.DataType + " " + propertyName + ",";
                    commentPara += "/// <param name={0}" + propertyName + "{0} >This is primary key to delete.</param>\r\n";

                }
            }
            commentPara = string.Format(commentPara, '"');
            comment = "\r\n/// <summary>\r\n";
            comment += "/// Delete " + table.Name + " object. \r\n";
            comment += "/// </summary>\r\n";
            comment += commentPara;
            comment += "/// <returns>True/False.</returns>\r\n";

            deleteFunctionPara = deleteFunctionPara.Substring(0, deleteFunctionPara.Length - 1);
            string delete = comment + string.Format(@"
            public static bool Delete({4})
    {1}
      String methodName = {3}Delete{0}{3};
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}

      try
      {1}
        DbCommand dbCommand = ManagerDao.GetStoredProcCommand({3}spDelete{0}{3});", table.Name, '{', '}', '"', deleteFunctionPara);

            delete += deleteStrorePara + string.Format(@"        
         //Add value returnValue  paramater.
        ManagerDao.AddParameter(dbCommand, {0}returnValue{0}, DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
        try
        {1}
          ManagerDao.ExecuteNonQuery(dbCommand);        
          int parameterValue = (int)ManagerDao.GetParameterValue(dbCommand, {3}returnValue{3});
          if (parameterValue == 1)
          {1}
            return true;
          {2}
        {2}
        catch (Exception)
        {1}
          throw;
        {2}
        return false;
      {2}
      catch (Exception e)
      {1}
        //write error message to log file.
        logger.Error(methodName, e);
        return false;
      {2}
    {2}", '"', "{", "}", '"');
            return delete;
        }
        private string SetFooter()
        {
            string footer = @"  
           
	                }
                }";
            return footer;
        }
        /// <summary>
        /// Gen function load object to Control
        /// Nguyen Van Ty
        /// 27/05/2009
        /// 
        /// </summary>
        private string CommonGetObjectToControl()
        {
            string get = string.Format(@"
             /// <summary>
        /// Get List object to fill control(combobox, listbox,...).
        /// </summary>
        /// <param name=""t"">Condition for search.</param>
        /// <returns>List {0}ToControl object.</returns>
            public static List<{0}ToControl> Get{0}ToControl({0}ToControlCondition t)
    {1}
      String methodName = ""Get" + table.Name + @"ToControl"";
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}
      try
      {1}
        
         List<{0}ToControl> list{0} = new List<{0}ToControl>();
        DbCommand cmd = ManagerDao.GetStoredProcCommand(""spGet{0}ToControl"");" + SetParamsSearch() + @"

        IDataReader reader = ManagerDao.ExecuteReader(cmd);
        while (reader.Read())
        {1}
            list{0}.Add(Get{0}ToControlByDataReader(reader));
        {2}
        reader.Close();
        return list{0};
      {2}
      catch (System.Exception e)
      {1}
        logger.Error(methodName, e);
        return null;
      {2}
    {2}", table.Name, "{", "}");
            return get;
        }

        private string GetTableToControlByDataReader()
        {
            string reader = string.Format(@"
              /// <summary>
        /// Get {0}ToControl object form DataReader.
        /// </summary>
        /// <param name=""reader"">Source Reader.</param>
        /// <returns>{0}ToControl Object.</returns>
            private static {0}ToControl Get{0}ToControlByDataReader(IDataReader reader)
    {1}
      String methodName = ""Get" + table.Name + @"ToControlByDataReader"";
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}
        try
      {1}
        {0}ToControl result = new {0}ToControl();", table.Name, "{", "}", '"');
            foreach (Utils.Column col in table.Columns)
            {
                if (col.Name == this.fieldValue || col.Name == this.fieldDisplay)
                {
                    /*string s = "";
                    if (col.DataType.ToUpper() == "int".ToUpper() || col.DataType.ToUpper() == "datetime".ToUpper())
                        s = string.Format(@"{0}.Parse(reader[{1}{2}{1}].ToString())", col.DataType, '"', Utils.Utility.ConvertToPropertyName(col.Name));
                    else
                        s = string.Format(@"({0})reader[{1}{2}{1}]", col.DataType, '"', Utils.Utility.ConvertToPropertyName(col.Name));*/
                    string s = col.DataType.ToLower();
                    reader += string.Format(@"
            //read {2} field data.
            result.{2} =ManagerDao.Get{3}DataFromDataReader(reader,{0}{2}{0});
           ", '"', table.Name, Utils.Utility.ConvertToPropertyName(col.Name), s);
                }
            }
            /*if (table.IsMultilanguage && !table.Name.Contains(Utils.Utility.MultilanguageTableName))
            {
                reader += string.Format("{0}.{0}{1}{2}={0}{1}.GetAllLanguageofItem();", table.Name, Utils.Utility.MultilanguageTableName, Utils.Utility.MultilanguageTableNameList);
            }*/
            reader += string.Format(@"
             return result;
      {2}
      catch (Exception e)
      {1}
        logger.Error(methodName, e);
        return null;
      {2}
    {2}", table.Name, "{", "}");
            return reader;
        }
        /// <summary>
        /// Search object by Some Condition, return toatalRow
        /// </summary>
        private string ComonSearchByCondition_TotalRow()
        {
            // search += SetParams(0);
            string search = @"
             /// <summary>
        /// Search {0} object in table {0} with condition is t object.
        /// </summary>
        /// <param name=""t"">Condition for Search.</param>
        /// <param name=""pageIndex"">pageindex is postion to begin get data.</param>
        /// <param name=""pageSize""> Number of records will be returned. </param>
        /// <param name=""totalRow"">  total records in this table.</param>
        /// <returns>List {0}Result object.</returns>
           /*  public static List<{0}Result> Search{0}SomeCondition({0}Condition t, int pageIndex, int pageSize,ref int totalRow)
                {1}
                 String methodName = ""Search" + table.Name + @"SomeCondition"";
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}

      try
      {1}
        List<{0}Result> list{0} = new List<{0}Result>();
        DbCommand cmd = ManagerDao.GetStoredProcCommand({3}spSearch{0}ByCondition{3});";
            search += SetParamsSearch();
            search += @"
                 //Add value PageIndex  paramater.
                ManagerDao.AddInParameter(cmd, {3}PageIndex{3}, DbType.Int32, pageIndex);
                //Add value PageSize  paramater.
                ManagerDao.AddInParameter(cmd, {3}PageSize{3}, DbType.Int32, pageSize);";
            search += @"
          using (IDataReader reader = ManagerDao.ExecuteReader(cmd))
        {1}
          while (reader.Read())
          {1}
            list{0}.Add(Get{0}ResultByDataReader(reader,ref totalRow));
          {2}
          reader.Close();
        {2}

        return list{0};
      {2}
      catch (Exception ex)
      {1}
        //write error message to log file.
        logger.Error(methodName, ex);
        return null;
      {2}
    {2}*/";
            search = string.Format(search, table.Name, "{", "}", '"');
            return search;
        }
        /// <summary>
        /// Search object by Some Condition , not return total Row
        /// </summary>
        private string ComonSearchByCondition()
        {
            return string.Empty;
            string search = @"
             /// <summary>
        /// Search {0} object in table {0} with condition is t object.
        /// </summary>
        /// <param name=""t"">Condition for Search</param>
        /// <param name=""pageIndex"">pageindex is postion to begin get data.</param>
        /// <param name=""pageSize""> Number of records will be returned. </param>       
        /// <returns>List {0}Result object.</returns>
            /* public static List<{0}Result> Search{0}SomeCondition({0}Condition t, int pageIndex, int pageSize)
                {1}
                 String methodName = ""Search" + table.Name + @"SomeCondition"";
      if (logger.IsDebugEnabled)
      {1}
        LoggingUtility.logMethodEntry(logger, methodName);
      {2}

      try
      {1}
        List<{0}Result> list{0} = new List<{0}Result>();
        DbCommand cmd = ManagerDao.GetStoredProcCommand({3}spSearch{0}ByCondition{3});";
            search += SetParamsSearch();
            search += @"
                 //Add value  PageIndex paramater.
                ManagerDao.AddInParameter(cmd, {3}PageIndex{3}, DbType.Int32, pageIndex);
                //Add value  PageSize paramater.
                ManagerDao.AddInParameter(cmd, {3}PageSize{3}, DbType.Int32, pageSize);";
            search += @"
          using (IDataReader reader = ManagerDao.ExecuteReader(cmd))
        {1}
          while (reader.Read())
          {1}
            list{0}.Add(Get{0}ResultByDataReader(reader));
          {2}
          reader.Close();
        {2}

        return list{0};
      {2}
      catch (Exception ex)
      {1}
        //write error message to log file
        logger.Error(methodName, ex);
        return null;
      {2}
    {2}*/";
            search = string.Format(search, table.Name, "{", "}", '"');
            return search;
        }
        public string ObjectClass
        {
            get
            {
                if (this.fieldDisplay != string.Empty && this.fieldValue != string.Empty)
                    this.objectClass = this.SetHeader() + this.SetConstructor() + this.CommonGetTable1DetailByDataReader(false) + this.GetTable1ResultByDataReader_TotalRow(true) + this.GetTable1ResultByDataReader_TotalRow(false) + this.SetCommonInsert() + this.CommonUpdate() + this.CommonGet() + CommonGetByLanguage() + this.ComonGetall() + ComonGetallByLanguage() + this.ComonDelete() + this.CommonGetObjectToControl() + this.ComonSearchByCondition_TotalRow() + GetTableToControlByDataReader() + this.ComonSearchByCondition() + GetTable1ResultByDataReader(true) + GetTable1ResultByDataReader(false) + this.GetAllLanguageofItem() + this.SetFooter();
                else
                    this.objectClass = this.SetHeader() + this.SetConstructor() +  this.CommonGetTable1DetailByDataReader(false) + this.GetTable1ResultByDataReader_TotalRow(true) + this.GetTable1ResultByDataReader_TotalRow(false) + this.SetCommonInsert() + this.CommonUpdate() + this.CommonGet() + CommonGetByLanguage() + this.ComonGetall() + ComonGetallByLanguage() + this.ComonSearchByCondition_TotalRow() + this.ComonDelete() + this.ComonSearchByCondition() + GetTable1ResultByDataReader(true) + GetTable1ResultByDataReader(false) + this.GetAllLanguageofItem() + this.SetFooter();
                return this.objectClass;
            }
        }
        private string SetParamFunctionGet()
        {
            string param = string.Empty;
            int i = 0;
            foreach (Utils.Column col in this.table.Columns)
            {
                if (col.IsPK || inKeyList(col.Name))
                {
                    param += string.Format(@"
                 //Add value {0}  paramater.
				ManagerDao.AddInParameter(dbCommnand, {0}, {1},{3});", '"' + Utils.Utility.ConvertToPropertyName(col.Name) + '"',
                                           Utils.Utility.ConvertParamType(col.SqlType),
                                           Utils.Utility.ConvertToPropertyName(col.DataType),
                                           col.Name);
                }
            }
            return param;
        }


    }
}
